<!-- eslint-disable vue/multi-word-component-names -->
<template>
  <div class="user-login">
    <!-- 背景装饰 -->
    <div class="bg-decoration">
      <div class="bg-circle bg-circle-1"></div>
      <div class="bg-circle bg-circle-2"></div>
      <div class="bg-circle bg-circle-3"></div>
      <div class="bg-grid"></div>
    </div>

    <!-- 登录容器 -->
    <div class="login-container" :class="{ 'shake': isShaking }">
      <!-- Logo和标题 -->
      <div class="login-header">
        <div class="logo-container">
          <div class="logo">E</div>
          <div class="logo-glow"></div>
        </div>
        <h1 class="login-title">EchoPlay</h1>
        <p class="login-subtitle">欢迎回来，开启你的AI对话之旅</p>
      </div>

      <!-- 登录表单 -->
      <form @submit.prevent="handleSubmit" class="login-form">
        <div class="form-group" :class="{ 'focused': focusedField === 'username' }">
          <label for="username" class="form-label">
            <user-icon class="label-icon" />
            用户名
          </label>
          <input
            id="username"
            v-model="username"
            type="text"
            placeholder="请输入用户名"
            class="form-input"
            @focus="focusedField = 'username'"
            @blur="focusedField = ''"
            required
          />
          <div class="input-border"></div>
        </div>

        <div class="form-group" :class="{ 'focused': focusedField === 'password' }">
          <label for="password" class="form-label">
            <lock-on-icon class="label-icon" />
            密码
          </label>
          <div class="password-wrapper">
            <input
              id="password"
              v-model="password"
              :type="showPassword ? 'text' : 'password'"
              placeholder="请输入密码"
              class="form-input"
              @focus="focusedField = 'password'"
              @blur="focusedField = ''"
              required
            />
            <button
              type="button"
              class="password-toggle"
              @click="showPassword = !showPassword"
              :aria-label="showPassword ? '隐藏密码' : '显示密码'"
            >
              <browse-icon v-if="showPassword" />
              <browse-off-icon v-else />
            </button>
          </div>
          <div class="input-border"></div>
        </div>

        <!-- 登录按钮 -->
        <button type="submit" class="login-btn" :disabled="isLoading">
          <div class="btn-content">
            <loading-icon v-if="isLoading" class="loading-icon" />
            <login-icon v-else class="btn-icon" />
            <span>{{ isLoading ? '登录中...' : '登录' }}</span>
          </div>
          <div class="btn-glow"></div>
        </button>

        <!-- 错误信息 -->
        <transition name="error-fade">
          <div v-if="errorMessage" class="error-message">
            <close-circle-icon class="error-icon" />
            {{ errorMessage }}
          </div>
        </transition>
      </form>

      <!-- 底部装饰 -->
      <div class="login-footer">
        <div class="footer-text">
          <span>首次使用？</span>
          <a href="#" class="footer-link">联系管理员</a>
        </div>
      </div>
    </div>

    <!-- 粒子效果容器 -->
    <div class="particles-container" ref="particlesContainer"></div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue';
import { useRouter } from 'vue-router';
import { useUserStore } from '@/stores/user';
import apiClient, { type ApiResponse } from '@/utils/api';
import { 
  UserIcon, 
  LockOnIcon, 
  BrowseIcon, 
  BrowseOffIcon, 
  LoginIcon, 
  LoadingIcon, 
  CloseCircleIcon 
} from 'tdesign-icons-vue-next';

// 定义响应式数据
const username = ref<string>('');
const password = ref<string>('');
const isLoading = ref<boolean>(false);
const errorMessage = ref<string>('');
const focusedField = ref<string>('');
const showPassword = ref<boolean>(false);
const isShaking = ref<boolean>(false);
const particlesContainer = ref<HTMLElement>();

const router = useRouter();
const userStore = useUserStore();

// 定义登录响应的数据结构类型
interface LoginResult {
  username: string;
  nickname: string;
  avatar?: string;
  permissions: string[];
  token: string;
}

// 粒子动画
const particles: Array<{
  x: number;
  y: number;
  vx: number;
  vy: number;
  opacity: number;
  size: number;
}> = [];
let animationId: number;

const createParticles = () => {
  if (!particlesContainer.value) return;
  
  const container = particlesContainer.value;
  const rect = container.getBoundingClientRect();
  
  for (let i = 0; i < 50; i++) {
    particles.push({
      x: Math.random() * rect.width,
      y: Math.random() * rect.height,
      vx: (Math.random() - 0.5) * 0.5,
      vy: (Math.random() - 0.5) * 0.5,
      opacity: Math.random() * 0.5 + 0.1,
      size: Math.random() * 2 + 1
    });
  }
};

const animateParticles = () => {
  if (!particlesContainer.value) return;
  
  const container = particlesContainer.value;
  const rect = container.getBoundingClientRect();
  
  // 清除之前的粒子
  container.innerHTML = '';
  
  particles.forEach((particle) => {
    // 更新位置
    particle.x += particle.vx;
    particle.y += particle.vy;
    
    // 边界检测
    if (particle.x < 0 || particle.x > rect.width) particle.vx *= -1;
    if (particle.y < 0 || particle.y > rect.height) particle.vy *= -1;
    
    // 创建粒子元素
    const dot = document.createElement('div');
    dot.className = 'particle';
    dot.style.left = particle.x + 'px';
    dot.style.top = particle.y + 'px';
    dot.style.opacity = particle.opacity.toString();
    dot.style.width = particle.size + 'px';
    dot.style.height = particle.size + 'px';
    
    container.appendChild(dot);
  });
  
  animationId = requestAnimationFrame(animateParticles);
};

// 震动动画
const triggerShake = () => {
  isShaking.value = true;
  setTimeout(() => {
    isShaking.value = false;
  }, 500);
};

// 登录提交函数
const handleSubmit = async () => {
  isLoading.value = true;
  errorMessage.value = '';
  
  try {
    const response = await apiClient.post('/auth/login', {
      username: username.value,
      password: password.value
    });
    
    // 从 response.data 中获取实际数据
    const data = response.data as ApiResponse<LoginResult>;
    
    // 检查业务逻辑是否成功
    if (data.success) {
      // 登录成功，保存用户信息和token
      userStore.setUserInfo({
        username: data.result.username,
        nickname: data.result.nickname,
        permissions: data.result.permissions,
        token: data.result.token,
        avatar: data.result.avatar || ''
      });
      
      // 成功提示
      const successMessage = document.createElement('div');
      successMessage.className = 'success-toast';
      successMessage.textContent = '登录成功！';
      document.body.appendChild(successMessage);
      
      setTimeout(() => {
        document.body.removeChild(successMessage);
      }, 2000);
      
      // 延迟跳转，让用户看到成功提示
      setTimeout(() => {
        router.push('/home');
      }, 1000);
    } else {
      // 业务逻辑失败（如用户名密码错误）
      errorMessage.value = data.message || '登录失败，请检查用户名和密码。';
      triggerShake();
    }
    
  } catch (error: unknown) {
    const errorMsg = error instanceof Error ? error.message : '登录失败，请重试。';
    errorMessage.value = errorMsg;
    triggerShake();
  } finally {
    isLoading.value = false;
  }
};

onMounted(() => {
  createParticles();
  animateParticles();
});

onUnmounted(() => {
  if (animationId) {
    cancelAnimationFrame(animationId);
  }
});
</script>

<style scoped>
.user-login {
  min-height: 100vh;
  background: radial-gradient(1200px 600px at 20% -10%, rgba(124,77,255,0.15), transparent), #0b0b0b;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
  position: relative;
  overflow: hidden;
}

/* 背景装饰 */
.bg-decoration {
  position: absolute;
  inset: 0;
  pointer-events: none;
  z-index: 1;
}

.bg-circle {
  position: absolute;
  border-radius: 50%;
  background: linear-gradient(135deg, rgba(124,77,255,0.1), rgba(167,139,250,0.05));
  filter: blur(1px);
  animation: float 20s infinite ease-in-out;
}

.bg-circle-1 {
  width: 300px;
  height: 300px;
  top: -150px;
  right: -150px;
  animation-delay: 0s;
}

.bg-circle-2 {
  width: 200px;
  height: 200px;
  bottom: -100px;
  left: -100px;
  animation-delay: -7s;
}

.bg-circle-3 {
  width: 150px;
  height: 150px;
  top: 50%;
  right: 10%;
  animation-delay: -14s;
}

.bg-grid {
  position: absolute;
  inset: 0;
  background-image: 
    linear-gradient(rgba(124,77,255,0.03) 1px, transparent 1px),
    linear-gradient(90deg, rgba(124,77,255,0.03) 1px, transparent 1px);
  background-size: 50px 50px;
  animation: grid-move 30s linear infinite;
}

@keyframes float {
  0%, 100% { transform: translateY(0px) rotate(0deg); }
  33% { transform: translateY(-20px) rotate(120deg); }
  66% { transform: translateY(10px) rotate(240deg); }
}

@keyframes grid-move {
  0% { transform: translate(0, 0); }
  100% { transform: translate(50px, 50px); }
}

/* 登录容器 */
.login-container {
  background: rgba(20, 20, 20, 0.8);
  backdrop-filter: blur(20px);
  border: 1px solid rgba(124,77,255,0.2);
  border-radius: 24px;
  padding: 40px;
  width: 100%;
  max-width: 420px;
  position: relative;
  z-index: 2;
  box-shadow: 
    0 20px 40px rgba(0,0,0,0.3),
    0 0 0 1px rgba(255,255,255,0.05) inset;
  transition: all 0.3s ease;
}

.login-container:hover {
  transform: translateY(-2px);
  box-shadow: 
    0 25px 50px rgba(0,0,0,0.4),
    0 0 0 1px rgba(124,77,255,0.3) inset;
}

.login-container.shake {
  animation: shake 0.5s ease-in-out;
}

@keyframes shake {
  0%, 100% { transform: translateX(0); }
  25% { transform: translateX(-5px); }
  75% { transform: translateX(5px); }
}

/* 登录头部 */
.login-header {
  text-align: center;
  margin-bottom: 32px;
}

.logo-container {
  position: relative;
  display: inline-block;
  margin-bottom: 16px;
}

.logo {
  width: 60px;
  height: 60px;
  border-radius: 16px;
  background: linear-gradient(135deg, #7c4dff, #a78bfa);
  display: flex;
  align-items: center;
  justify-content: center;
  color: #0b0b0b;
  font-weight: 900;
  font-size: 28px;
  position: relative;
  z-index: 2;
  box-shadow: 0 8px 32px rgba(124,77,255,0.3);
}

.logo-glow {
  position: absolute;
  inset: -4px;
  background: linear-gradient(135deg, #7c4dff, #a78bfa);
  border-radius: 20px;
  filter: blur(8px);
  opacity: 0.6;
  z-index: 1;
  animation: pulse 2s ease-in-out infinite;
}

@keyframes pulse {
  0%, 100% { opacity: 0.6; transform: scale(1); }
  50% { opacity: 0.8; transform: scale(1.05); }
}

.login-title {
  font-size: 32px;
  font-weight: 800;
  margin: 0 0 8px;
  background: linear-gradient(90deg, #c7b8ff, #7c4dff 40%, #a78bfa);
  -webkit-background-clip: text;
  background-clip: text;
  color: transparent;
  letter-spacing: 0.6px;
}

.login-subtitle {
  color: #b5b5b5;
  margin: 0;
  font-size: 14px;
  font-weight: 400;
}

/* 表单样式 */
.login-form {
  margin-bottom: 24px;
}

.form-group {
  margin-bottom: 24px;
  position: relative;
}

.form-group.focused .form-label {
  color: #7c4dff;
}

.form-group.focused .input-border {
  transform: scaleX(1);
}

.form-label {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
  color: #e0e0e0;
  font-size: 14px;
  font-weight: 500;
  transition: color 0.3s ease;
}

.label-icon {
  width: 16px;
  height: 16px;
}

.form-input {
  width: 100%;
  padding: 16px 20px;
  background: rgba(255,255,255,0.05);
  border: 1px solid rgba(255,255,255,0.1);
  border-radius: 12px;
  color: #fff;
  font-size: 16px;
  transition: all 0.3s ease;
  position: relative;
}

.form-input:focus {
  outline: none;
  background: rgba(255,255,255,0.08);
  border-color: rgba(124,77,255,0.5);
  box-shadow: 0 0 0 3px rgba(124,77,255,0.1);
}

.form-input::placeholder {
  color: #888;
}

.password-wrapper {
  position: relative;
}

.password-toggle {
  position: absolute;
  right: 16px;
  top: 50%;
  transform: translateY(-50%);
  background: none;
  border: none;
  color: #888;
  cursor: pointer;
  padding: 4px;
  border-radius: 4px;
  transition: color 0.3s ease;
}

.password-toggle:hover {
  color: #7c4dff;
}

.input-border {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 2px;
  background: linear-gradient(90deg, #7c4dff, #a78bfa);
  transform: scaleX(0);
  transition: transform 0.3s ease;
  border-radius: 1px;
}

/* 登录按钮 */
.login-btn {
  width: 100%;
  padding: 16px 24px;
  background: linear-gradient(135deg, #7c4dff, #6a3cff);
  border: none;
  border-radius: 12px;
  color: #fff;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: all 0.3s ease;
  margin-bottom: 16px;
}

.login-btn:hover:not(:disabled) {
  transform: translateY(-1px);
  box-shadow: 0 8px 25px rgba(124,77,255,0.4);
}

.login-btn:active:not(:disabled) {
  transform: translateY(0);
}

.login-btn:disabled {
  opacity: 0.7;
  cursor: not-allowed;
}

.btn-content {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  position: relative;
  z-index: 2;
}

.btn-icon, .loading-icon {
  width: 18px;
  height: 18px;
}

.loading-icon {
  animation: spin 1s linear infinite;
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

.btn-glow {
  position: absolute;
  inset: 0;
  background: linear-gradient(135deg, rgba(255,255,255,0.2), transparent);
  opacity: 0;
  transition: opacity 0.3s ease;
}

.login-btn:hover:not(:disabled) .btn-glow {
  opacity: 1;
}

/* 错误信息 */
.error-message {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px 16px;
  background: rgba(244,67,54,0.1);
  border: 1px solid rgba(244,67,54,0.3);
  border-radius: 8px;
  color: #ff6b6b;
  font-size: 14px;
  margin-bottom: 16px;
}

.error-icon {
  width: 16px;
  height: 16px;
  flex-shrink: 0;
}

.error-fade-enter-active, .error-fade-leave-active {
  transition: all 0.3s ease;
}

.error-fade-enter-from, .error-fade-leave-to {
  opacity: 0;
  transform: translateY(-10px);
}

/* 底部 */
.login-footer {
  text-align: center;
}

.footer-text {
  color: #888;
  font-size: 14px;
}

.footer-link {
  color: #7c4dff;
  text-decoration: none;
  margin-left: 4px;
  transition: color 0.3s ease;
}

.footer-link:hover {
  color: #a78bfa;
}

/* 粒子效果 */
.particles-container {
  position: absolute;
  inset: 0;
  pointer-events: none;
  z-index: 1;
}

.particle {
  position: absolute;
  background: #7c4dff;
  border-radius: 50%;
  pointer-events: none;
}

/* 成功提示 */
:global(.success-toast) {
  position: fixed;
  top: 20px;
  right: 20px;
  background: linear-gradient(135deg, #4caf50, #45a049);
  color: white;
  padding: 12px 24px;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(76,175,80,0.3);
  z-index: 9999;
  animation: slideIn 0.3s ease;
}

@keyframes slideIn {
  from {
    transform: translateX(100%);
    opacity: 0;
  }
  to {
    transform: translateX(0);
    opacity: 1;
  }
}

/* 响应式设计 */
@media (max-width: 480px) {
  .login-container {
    padding: 24px;
    margin: 16px;
  }
  
  .login-title {
    font-size: 28px;
  }
  
  .logo {
    width: 50px;
    height: 50px;
    font-size: 24px;
  }
}
</style>